#!/bin/bash
#该程序的作用是监测某个程序是否执行结束，在执行结束前不断的监测其CPU使用率、内存使用率和磁盘使用量，并写入到日志文件中

# 设置要监控的程序的PID
PROGRAM_PID=$1

CURRENT_TIME=$(date "+%Y%m%d_%H%M%S")
OUTPUT_FILE="./memory_usage.${CURRENT_TIME}.log"

# 检查PID是否存在
if [ -z "$PROGRAM_PID" ]; then
    echo "Usage: $0 <PID>"
    exit 1
fi

# 创建输出文件并添加标题
printf "%-20s %-15s %-18s %-15s\n" "Timestamp" "CPU Usage (%)" "Memory Usage (MB)" "Disk Space (MB)" > $OUTPUT_FILE
printf "%-20s %-15s %-18s %-15s\n" "Timestamp" "CPU Usage (%)" "Memory Usage (MB)" "Disk Space (MB)"
# echo "Timestamp, CPU Usage (%), Memory Usage (MB), Disk Space (MB)" > $OUTPUT_FILE
# echo "Timestamp, CPU Usage (%), Memory Usage (MB), Disk Space (MB)"

# 无限循环监控并记录信息
while true; do
    # 检查程序是否仍然运行
    if ! kill -0 $PROGRAM_PID 2>/dev/null; then
        echo "Program with PID $PROGRAM_PID has exited."
        break
    fi
    
    # 获取当前时间
    TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
    
    # 获取CPU使用情况（只获取总CPU使用率）
    CPU_USAGE=$(top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print 100 - $1}')
    
    # 获取内存使用情况
    MEMORY_USAGE=$(free -m | awk '/^Mem/ { print $3 }')
    
    # 获取磁盘空间剩余情况（根目录为例）
    DISK_SPACE=$(df -m / | awk 'NR==2 { print $4 }')
    
    # 写入文件
    printf "%-20s %-15.2f %-18s %-15s\n" "$TIMESTAMP" "$CPU_USAGE" "$MEMORY_USAGE" "$DISK_SPACE" >> $OUTPUT_FILE
    printf "%-20s %-15.2f %-18s %-15s\n" "$TIMESTAMP" "$CPU_USAGE" "$MEMORY_USAGE" "$DISK_SPACE"
    
    # 等待一分钟
    sleep 60
done
